var tokenList = null;
var userInfo = null;

function signIn () {
  nebPay.simulateCall(dappAddress, "0", "getUserInfo", JSON.stringify([]), {
    listener: function(res) {
      if(res.result == '' && res.execute_err == 'contract check failed') {
          toast('合约检测失败，请检查浏览器钱包插件环境！');
          return;
      }
      
      var info = res.result && JSON.parse(JSON.parse(res.result));
      if (info) {
        userInfo = info;
        getToken()
      }
    }
  })
}

signIn()

function getToken () {
  nebPay.simulateCall(dappAddress, "0", "getGive", JSON.stringify([]), {
    listener: function(res) {
      if(res.result == '' && res.execute_err == 'contract check failed') {
          toast('合约检测失败，请检查浏览器钱包插件环境！');
          return;
      }
      
      var info = res.result && JSON.parse(JSON.parse(res.result));
      if (info) {
        renderHtml(info);
        $('#loading').hide();
      }
    }
  })
}

function renderHtml (data) {
  var html = '';
  for (var i = 0; i < data.length; i++) {
    var isOngoing = data[i].surplus - data[i].itemNum < 1;
    var isTaken = false;
    for (var y = 0; y < userInfo.giveId.length; y++) {
      if (userInfo.giveId[y] == data[i].id) {
        isTaken = true
      }
    }

    html += '<li class="'+ ((!isOngoing && !isTaken) ? 'blue' : 'red') +'">'
      +'<div>'+data[i].tokenName+'</div><div>每人限领'+data[i].itemNum+'</div>'
      + '<div>'+(isOngoing ? '已结束' : '进行中' )+'</div>'
      + '<div data-name="'+data[i].tokenName+'"  data-id="'+((!isOngoing && !isTaken) ? data[i].id : 0)+'">'+(isTaken ? '已领取' : '领取')+'</div></li>';
  }

  $('ul').html(html);
}

$('ul').on('click', 'div', function () {
  var id = $(this).data('id');
  if (+id == 0) {
    return false;
  }
  var name = $(this).data('name');
  nebPay.call(dappAddress, "0", "receiveGive", JSON.stringify([name, id]), { 
    listener: function(res) {
      toast(res.txhash ? '领取空投成功,请稍等30秒去代币余额查看余额..注意不可重复领取！' : '领取空投失败！！！');
    }
  })
})
